import vine from '@vinejs/vine'
import { createMemberSchema } from '#validators/member'
import { createDictSchema } from '#validators/dict'
import { createCardRightSchema } from '#validators/card_right'
import { createServiceRightSchema } from '#validators/service_right'

const cardsOrServices = vine
  .group([
    vine.group.if((data) => 'cards' in data, {
      cards: vine.array(
        vine.object({
          ...createMemberSchema.getProperties(),
          id: vine.number().positive(),
          initJson: createCardRightSchema,
          salePrice: vine.number().positive(),
          actualStoreAmount: vine.number().positive(),
          actualGiftAmount: vine.number().positive(),
        })
      ),
    }),
    vine.group.if((data) => 'services' in data, {
      services: vine.array(
        vine.object({
          ...createServiceRightSchema.getProperties(),
          id: vine.number().positive(),
          initJson: createServiceRightSchema,
          salePrice: vine.number().positive(),
          times: vine.number().positive(),
          giftTimes: vine.number().positive(),
        })
      ),
    }),
  ])
  .otherwise((_, field) => {
    field.report('购买会员或服务才能办卡', 'unknown_create_card', field)
  })

export const createCashierCardSchema = vine
  .object({
    fkSourceId: vine.number().positive(),
    billNo: vine.string().optional(),
    billDate: vine.date(),

    customerName: vine.string().maxLength(20).optional(),
    customerSex: vine.number().range([0, 2]).optional(),
    customerPhone: vine.string().maxLength(11).optional(),
    actualPrice: vine.number().positive(),
    actualPayPrice: vine.number().positive(),
    totalAmount: vine.number().positive(),
    member: createMemberSchema,
    cards: vine.array(
      vine.object({
        ...createMemberSchema.getProperties(),
        id: vine.number().positive(),
        initJson: createCardRightSchema,
        salePrice: vine.number().positive(),
        actualStoreAmount: vine.number().positive(),
        actualGiftAmount: vine.number().positive(),
      })
    ),
    paymentMethod: vine.array(
      vine.object({
        ...createDictSchema.getProperties(),
        id: vine.number().positive(),
        normalPrice: vine.number().positive(),
        actualPrice: vine.number().positive(),
        actualPayPrice: vine.number().positive(),
      })
    ),
  })
  .merge(cardsOrServices)

export const createCashierCardValidator = vine.compile(createCashierCardSchema)
